package top.forforever.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.forforever.srb.common.exception.BusinessException;
import top.forforever.srb.common.result.ResponseEnum;
import top.forforever.srb.common.util.MD5;
import top.forforever.srb.oss.prop.OssProperties;
import top.forforever.srb.oss.service.OssService;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @create: 2023/5/4
 * @Description:
 * @FileName: OssServiceImpl
 * @自定义内容：
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadImage(MultipartFile multipartFile,String module) {
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(OssProperties.END_POINT,OssProperties.KEY_ID,OssProperties.KEY_SECRET);

            //文件名 = 文件类别/年/月/日/文件名.后缀
            String ext = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());

            String filename = module + //文件类别
                       new DateTime().toString("/yyyy/MM/dd/") + //年月日
                       UUID.randomUUID().toString().replaceAll("-", "") + // uuid
                       "." + ext; // 文件名.后缀

            ossClient.putObject(OssProperties.BUCKET_NAME,filename,multipartFile.getInputStream());

            StringBuffer buffer =new StringBuffer()
                        .append("https://")
                        .append("%s")
                        .append(".")
                        .append("%s")
                        .append("/")
                        .append("%s");
            return String.format(buffer.toString(),OssProperties.BUCKET_NAME,OssProperties.END_POINT,filename);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        } finally {
            if ( ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    @Override
    public void deleteImage(String url) {
        //url 去掉 https://桶名.节点名/
        String deleteName = url.substring(("https://tj-srb.oss-cn-shenzhen.aliyuncs.com/").length());
        OSS ossClient = new OSSClientBuilder().build(OssProperties.END_POINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        ossClient.deleteObject(OssProperties.BUCKET_NAME,deleteName);
        ossClient.shutdown();
    }

}
